<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="50%" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/Drawer';
import { formSchema } from '../data/data';
import {Api} from "../data/api";
// 声明Emits
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue,formSubmit, validate }] = useForm({
  rowKey: 'htmlId',
  saveApi: Api.add,
  updateApi: Api.update,
  schemas: formSchema,
  labelWidth: 120,
});

const [registerDrawer, { setDrawerProps,changeLoading, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  changeLoading(false);
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    await setFieldsValue({
      ...data.record,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增服务协议' : '编辑服务协议'));

async function handleSubmit() {
  try {
    changeLoading(true);
    await formSubmit({
      emit:emit
    });
    closeDrawer();
  } finally {
    changeLoading(false);
  }
}
</script>
